/** Actions
 *  动作配置组件
 */

import React, {useEffect, useRef, useState} from 'react';
import {Icon} from 'antd';
import Modal from 'src/components/Modal';
import ActionsConfig from './config';
import ResultStyle from 'src/routers/Strategy/Strategy/Component/test/resultStyle';
import ActionLabel from './label';
import {cloneDeep} from 'lodash';
import './index.less';
import {randomKey} from '../../utils/utils';
import useRiskTypes from "../../hook/useRiskTypes";
import {connect} from "react-redux";

function Actions(props) {
  const { actions, logs = {}, cellId, isHit: pIsHit, using_variables, variable, disabled } = props;
  const [value, setValue] = useState([]);
  const [isHit, setIsHit] = useState(false);
  const [riskLevels, setRiskLevels] = useState([]); // 风险级别
  const actionConfig = useRef(null);

  const isHasLog = Object.keys(logs).length > 0;
  const riskTypes = props.riskTypes ? props.riskTypes: useRiskTypes();

  useEffect(() => {
    if (!props.riskLevels) {
      let riskLevels = props.codes.risk_level ?
          props.codes.risk_level.map(it => {
            return {code: it.key, name: it.value};
          })
          : [];
      setRiskLevels(riskLevels);
    } else {
      setRiskLevels(props.riskLevels);
    }
  }, [props.riskLevels]);
  useEffect(() => {
    if (props.value && actions && actions.length > 0) {
      const values = createUsefullData(props.value);
      setValue(values);
    }
  }, [props.value, props.actions]);

  // cellId 存在时 通过传入cell的logs判断是否命中 适用于决策表 决策矩阵
  // 其他组件时 直接拿取传入的 pIsHit 命中情况 但是也需要logs中variables来渲染变量的值
  useEffect(() => {
    cellId && logs && isHasLog && getCurrActionLog();
  }, [logs]);
  useEffect(() => {
    !cellId && (pIsHit !== undefined ? setIsHit(pIsHit) : setIsHit(false));
  }, [pIsHit]);

  // 组装成前端可用的数据，将value和 函数数据进行组装，因为函数数据是引用
  function createUsefullData(value) {
    const temp = cloneDeep(value);
    return temp
      .map((item) => {
        const cur = cloneDeep(actions.find((it) => it.code === item.code));
        if (cur) {
          cur.parameters =
            cur.parameters &&
            cur.parameters.map((param, index) => {
              const itemParam = (item.parameters && item.parameters[index]) || {};
              if (
                itemParam.value &&
                Object.keys(itemParam.value).length &&
                itemParam.value.var_code &&
                Object.prototype.toString.call(itemParam.value.var_code) === '[object String]' &&
                itemParam.value.var_code.includes(',')
              ) {
                itemParam.value.var_code = itemParam.value.var_code.split(',');
              }
              return {
                ...param,
                ...itemParam,
              };
            });
        }
        // console.log('cur:');
        // console.log(cur);
        return cur;
      })
      .filter(Boolean);
  }

  // 获取当前cell的测试日志
  const getCurrActionLog = () => {
    const { rules } = logs;
    const tempObj = rules.find((item) => item.id === cellId) || {};
    setIsHit(tempObj.hit);
  };

  const openConfig = () => {
    const modelIds = randomKey();
    const i = Modal.open({
      title: '配置动作',
      width: 840,
      key: modelIds,
      bgClickFlase: true,
      content: (
        <div
          style={{
            marginBottom: '20px',
            minHeight: '300px',
          }}
        >
          <ActionsConfig
            modelId={modelIds}
            variable={variable}
            using_variables={using_variables}
            disabled={disabled}
            value={value}
            createRef={actionConfig}
            actions={actions}
            riskTypes={riskTypes}
            riskLevels={riskLevels}
            allowEmpyt={props.allowEmpyt}
          />
        </div>
      ),
      ok: () => {
        actionConfig.current.getValue((value, error) => {
          if (!error) {
            const newValue = value.map((item) => {
              item.parameters = item.parameters.map(({ value }) => {
                const temp = {
                  ...value,
                };
                if (Array.isArray(temp.var_code)) {
                  temp.var_code = temp.var_code.join(',');
                }
                return {
                  value: temp,
                };
              });
              return item;
            });
            setValue(value);
            props.onChange && props.onChange(newValue);
            Modal.close(i);
          }
        });
      },
      cancel: () => {},
    });
  };
  return (
    <div className={`flex actions ${props.isGlobalCompare && 'global-compare'}`}>
      <div>
        {value.map((item, index) => {
          const Label = (newProps) => (
            <ActionLabel
              {...props}
              key={index}
              item={item}
              value={props.value}
              index={index}
              isHit={isHit}
              riskTypes={riskTypes}
              riskLevels={riskLevels}
              {...newProps}
            />
          );
          return isHit ? (
            <ResultStyle hightLight isHit={isHit} key={index} top={Label({ isHit: false })} bottom={Label()} />
          ) : (
            Label()
          );
        })}
      </div>
      {!disabled && <Icon type='edit' className='operate-edit' onClick={openConfig} />}
    </div>
  );
}

function mapStateToProps(state) {
  return {
    codes: {
      ...state.code,
    },
  };
}
export default connect(mapStateToProps)(Actions);